package com.yanqu.client.message;

import com.google.protobuf.Message;
import com.yanqu.road.define.YanQuMessageDefine;
import com.yanqu.road.message.YanQuMessage;

import io.vertx.core.buffer.Buffer;


public class Encrypt {

    private int getMessageSize(Message pbMessage, YanQuMessage message) {
        int size = YanQuMessageDefine.HEADER_SIZE;
        if (pbMessage == null) {
            byte[] bytes = message.getBytes();
            if (bytes != null) {
                size = YanQuMessageDefine.HEADER_SIZE + bytes.length;
            }
        } else {
            size = YanQuMessageDefine.HEADER_SIZE + pbMessage.getSerializedSize();
        }

        return size;
    }


    public Buffer encodeYanquMessage(YanQuMessage message) {
        Message pbMessage = message.getMessage();
        int messageSize = getMessageSize(pbMessage, message);
        Buffer buffer = Buffer.buffer();
        this.writeHeader(message, messageSize, buffer);
        return buffer;
    }

    private void writeHeader(YanQuMessage yanQuMessage, int len, Buffer out) {
        out.appendShort(YanQuMessageDefine.HEADER_MARK);
        out.appendInt(len);
        out.appendInt(yanQuMessage.getCode());
        out.appendLong(yanQuMessage.getPlayerId());
        if (yanQuMessage.getMessage() != null) {
            out.appendBytes(yanQuMessage.getMessage().toByteArray());
        } else if (yanQuMessage.getBytes() != null) {
            if (yanQuMessage.getMsgDataLength() != 0) {
                out.appendBytes(yanQuMessage.getBytes(), 0, yanQuMessage.getMsgDataLength());
            } else {
                out.appendBytes(yanQuMessage.getBytes());
            }
        }
    }
}
